package com.example.xiaozu.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.xiaozu.R;
import com.example.xiaozu.Adapter.AccountAdapter;
import com.example.xiaozu.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AccountManageActivity extends AppCompatActivity
        implements AccountAdapter.AccountActionListener {

    private AccountAdapter adapter;
    private final List<User> accountList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_manage);

        loadAccounts();
        setupRecyclerView();
        setupAddButton();
    }

    private void loadAccounts() {
        SharedPreferences prefs = getSharedPreferences("users", MODE_PRIVATE);
        Map<String, ?> allEntries = prefs.getAll();

        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            if (entry.getKey().endsWith("_username")) {
                String username = (String) entry.getValue();
                String phone = prefs.getString(username + "_phone", "");
                boolean isAdmin = prefs.getBoolean(username + "_admin", false);
                accountList.add(new User(username, phone, "", isAdmin));
            }
        }
    }

    private void setupRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.rv_accounts);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AccountAdapter(this, accountList, this);
        recyclerView.setAdapter(adapter);
    }

    private void setupAddButton() {
        findViewById(R.id.btn_add_account).setOnClickListener(v -> {
            // 跳转到注册页面
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }

    @Override
    public void onEditAccount(User user) {
        // 跳转到修改密码页面
        Intent intent = new Intent(this, ChangePasswordActivity.class);
        intent.putExtra("username", user.getUsername());
        startActivity(intent);
    }

    @Override
    public void onDeleteAccount(int position, User user) {
        new AlertDialog.Builder(this)
                .setTitle("删除账号")
                .setMessage("确定删除账号 " + user.getUsername() + " 吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    deleteAccountFromPrefs(user.getUsername());
                    accountList.remove(position);
                    adapter.notifyItemRemoved(position);
                    Toast.makeText(this, "账号已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onToggleAdminStatus(int position, User user) {
        boolean newStatus = !user.isAdmin();
        updateAdminStatusInPrefs(user.getUsername(), newStatus);
        accountList.get(position).setAdmin(newStatus);
        adapter.notifyItemChanged(position);

        String message = newStatus ? "已设为管理员" : "已取消管理员权限";
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void deleteAccountFromPrefs(String username) {
        SharedPreferences.Editor editor = getSharedPreferences("users", MODE_PRIVATE).edit();
        editor.remove(username + "_username");
        editor.remove(username + "_phone");
        editor.remove(username + "_password");
        editor.remove(username + "_admin");
        editor.apply();
    }

    private void updateAdminStatusInPrefs(String username, boolean isAdmin) {
        getSharedPreferences("users", MODE_PRIVATE).edit()
                .putBoolean(username + "_admin", isAdmin)
                .apply();
    }
}